package com.ruoyi.web.Server.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.web.dao.sys.ResPassKeyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.web.domain.sys.UserPassKey;
import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class ResPassKeyService {

    @Autowired
    private ResPassKeyMapper passKeyMapper;

    @Autowired
    private RedisCache redisCache;

    // 生成新的邀请码
    public UserPassKey generatePassKey(Integer userId) {
        // 删除该用户之前的passkeys（可选）
        passKeyMapper.delete(new QueryWrapper<UserPassKey>().eq("user_id", userId));

        UserPassKey passKey = new UserPassKey();
        passKey.setUserId(userId);
        passKey.setPasskey(generateUniquePassKey());
        passKey.setCreateTime(LocalDateTime.now());
        passKey.setStatus(1); // 有效状态

        passKeyMapper.insert(passKey);

        // 将passkey缓存到Redis，有效期24小时
        redisCache.setCacheObject("passkey:" + passKey.getPasskey(), passKey, 24, TimeUnit.HOURS);

        return passKey;
    }

    // 验证Passkey是否有效
    public boolean isValidPassKey(String passKeyStr) {
        try {
            // 先从Redis获取
            UserPassKey passKey = redisCache.getCacheObject("passkey:" + passKeyStr);

            // Redis中没有，尝试从数据库获取
            if (passKey == null) {
                passKey = passKeyMapper.selectOne(
                        new QueryWrapper<UserPassKey>()
                                .eq("passkey", passKeyStr)
                );

                // 找不到记录
                if (passKey == null) return false;

                // 缓存到Redis
                redisCache.setCacheObject("passkey:" + passKeyStr, passKey, 24, TimeUnit.HOURS);
            }

            // 状态判断
            if (passKey.getStatus() != 1) return false; // 已标记失效

            // 是否过期
            if (passKey.isExpired()) {
                // 自动更新状态
                passKey.setStatus(0);
                passKeyMapper.updateById(passKey);
                redisCache.deleteObject("passkey:" + passKeyStr);
                return false;
            }

            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // 生成唯一的Passkey
    private String generateUniquePassKey() {
        String passKey;
        int maxAttempts = 5;

        // 确保生成的Passkey是唯一的
        for (int i = 0; i < maxAttempts; i++) {
            passKey = generateRandomPassKey();
            boolean exists = passKeyMapper.exists(
                    new QueryWrapper<UserPassKey>().eq("passkey", passKey)
            );

            if (!exists) {
                return passKey;
            }
        }

        throw new RuntimeException("无法生成唯一Passkey，请重试");
    }

    // 生成随机Passkey（8位字母数字组合）
    private String generateRandomPassKey() {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb = new StringBuilder(8);
        Random random = new Random();

        for (int i = 0; i < 8; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }

        return sb.toString();
    }
}
